package com.gaoyi.basemodule.basefragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.fragment.app.FragmentActivity;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.ViewModelProvider;
import androidx.lifecycle.ViewModelStoreOwner;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;

import com.gaoyi.basemodule.basevm.BaseViewModel;
import com.gaoyi.basemodule.baseCallback.IView;

import java.lang.reflect.ParameterizedType;

public abstract class BaseFragment<V extends ViewDataBinding, VM extends BaseViewModel> extends BasePermissionFragment {
    protected FragmentActivity mContext;
    protected V mBinding;
    protected VM mViewModel;
    protected NavController mController;
    protected LifecycleOwner mOwner;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = requireActivity();
        mViewModel = new ViewModelProvider(getOwner()).get(getViewModelClass());
        if (this instanceof IView) {
            mViewModel.attachView((IView) this);
        }
        getLifecycle().addObserver(mViewModel);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mBinding = DataBindingUtil.inflate(inflater, getLayoutId(), container, false);
        mOwner = getViewLifecycleOwner();
        mBinding.setLifecycleOwner(mOwner);
        mBinding.setVariable(initVariable(), mViewModel);
        initView();
        return mBinding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mController = Navigation.findNavController(view);
        initLiveData();
        initData();
    }

    protected abstract int getLayoutId();

    protected abstract void initView();

    protected abstract int initVariable();

    protected abstract void initLiveData();

    protected abstract void initData();

    /**
     * 区分是否与父容器共享数据
     * 是 return requireParentFragment()/requireActivity()
     * 否 return this
     */
    protected abstract ViewModelStoreOwner getOwner();

    Class<VM> getViewModelClass() {
        ParameterizedType type = (ParameterizedType) getClass().getGenericSuperclass();
        if (type == null) return null;
        return (Class<VM>) type.getActualTypeArguments()[1];
    }

    @Override
    public void onDestroyView() {
        mBinding.unbind();
        super.onDestroyView();
    }
}
